<template>
  <div>
    <el-card class="box-card">
      <el-breadcrumb separator="/" style="margin-bottom: 20px">
        <el-breadcrumb-item :to="{ path: '/welcome/supper' }"
          >办公用品申领</el-breadcrumb-item
        >
      </el-breadcrumb>
      <template>
        <el-row :gutter="20">
          <el-col :span="2"> 物品名称: </el-col>
          <!-- <i s:span="1">  目的地:</i> -->
          <el-col :span="3" class="demo-input-suffix">
            <el-input
              placeholder="物品名称"
              clearable
              style="display: inline"
              v-model="supper.suppliesName"
            >
              <!-- <i slot="prefix" class="el-input__icon el-icon-search"></i> -->
            </el-input>
          </el-col>
          <el-col :span="7">
            <el-button
              type="primary"
              icon="el-icon-search"
              style="display: inline"
              @click="search"
              >搜索</el-button
            >
          </el-col>
          <el-col :span="3">
            <el-button type="primary" @click="showAddDialog"
              ><i class="el-icon-plus"></i>添加</el-button
            >
          </el-col>
          <el-col :span="7">
            <el-button
              type="primary"
              icon="el-icon-search"
              style="display: inline"
              @click="exportData"
              >导出</el-button
            > 
          </el-col>
        </el-row>
      </template>
      <el-dialog
        title="办公用品申领:  "
        :close-on-click-modal="false"
        :visible.sync="addDialogVisible"
        :show-close="true"
      >
        <el-form :model="supper" ref="supper" :rules="rules">
          <el-form-item
            label="办公用品名称"
            prop="suppliesName"
            :label-width="formLabelWidth"
          >
            <el-input v-model="supper.suppliesName"></el-input>
          </el-form-item>
          <el-form-item
            label="规格型号"
            prop="suppliesType"
            :label-width="formLabelWidth"
          >
            <el-input v-model="supper.suppliesType"></el-input>
          </el-form-item>
          <el-form-item
            label="计量单位"
            prop="suppliesUnit"
            :label-width="formLabelWidth"
          >
            <el-radio-group v-model="supper.suppliesUnit">
              <el-radio :label="1">个</el-radio>
              <el-radio :label="2">本</el-radio>
              <el-radio :label="3">套 </el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item
            label="单价"
            prop="suppliesPrice"
            :label-width="formLabelWidth"
          >
            <el-input-number
              v-model="supper.suppliesPrice"
              :precision="2"
              :step="0.1"
              :max="100000"
            ></el-input-number>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="addUser('supper')">保存</el-button>
        </div>
      </el-dialog>

      <!-- <el-dialog
        title="信息:  "
        :close-on-click-modal="false"
        :visible.sync="addDialogVisibles"
        :show-close="true"
      >
        <el-form :model="car" ref="car" :rules="rules">
          <el-form-item
            label="信息"
            prop="departureTime"
            :label-width="formLabelWidth"
          >
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="addUser('car')">保存</el-button>
        </div> 
      </el-dialog> -->

      <el-dialog
        title="办公用品申领详情"
        :close-on-click-modal="false"
        :visible.sync="editDialogVisible"
        :show-close="true"
      >
        <!-- <el-form :model="car" ref="car" :rules="rules">
          <el-form-item
            label="部门名称"
            prop="car.id"
            :label-width="formLabelWidth"
          >
            <el-input v-model="car.id"></el-input>
          </el-form-item>
        </el-form> -->
        <!-- <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="updateUser('user')">保存</el-button>
        </div> -->
      </el-dialog>

      <el-table border :data="tableData" style="width: 100%; margin-top: 20px">
        <el-table-column prop="suppliesName" label="物品名称"></el-table-column>
        <el-table-column prop="suppliesType" label="规格型号"></el-table-column>
        <!-- <el-table-column prop="suppliesUnit">
       
        </el-table-column> -->
        <el-table-column label="计量单位">
          <template slot-scope="scope">
            <span v-if="scope.row.suppliesUnit === 1">个</span>
            <span v-if="scope.row.suppliesUnit === 2">本</span>
            <span v-if="scope.row.suppliesUnit === 3">套</span>
          </template>
        </el-table-column>
        <el-table-column prop="suppliesPrice" label="单价"></el-table-column>
        <el-table-column
          prop="suppliesProposerName"
          label="申请人"
        ></el-table-column>
        <el-table-column
          prop="suppliesStaticName"
          label="状态"
        ></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-row>
              <div style="text-align: center">
                <el-button
                  type="info"
                  plain
                  size="small"
                  @click="selectById(scope.row)"
                  >查看详情</el-button
                ><br />

                <el-button
                  type="info"
                  plain
                  size="small"
                  @click="deletes(scope.row)"
                  >取消订单</el-button
                >
              </div>
            </el-row>
          </template>
        </el-table-column>
      </el-table>
      <template>
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="params.pageIndex"
          :page-sizes="[5, 10, 15, 20]"
          :page-size="params.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="params.total"
        >
        </el-pagination>
      </template>
    </el-card>
  </div>
</template>
<script>
export default {
  data() {
    return {
      tableData: [],
      params: {
        pageSize: 5, // 每页显示5条记录
        pageIndex: 1, // 当前第几页
        total: 0, // 共几条记录去分页
      },
      supper: {
        //办公物品申领id
        suppliesId: 0,
        //名称
        suppliesName: "",
        //规格型号
        suppliesType: "",
        //计量单位1：个2：本3：套
        suppliesUnit: 1,
        //单价
        suppliesPrice: 0,
        //申请人id
        suppliesSysUsrId: 0,
        suppliesUnitName: "", //计量单位名称
        suppliesStaticId: 0, //状态Id
        suppliesProposerId: 0, //申请人id
        suppliesStaticName: 0, //状态Name
        suppliesProposerName: 0, //申请人Name
      },
      did: 0,

      addDialogVisible: false,
      editDialogVisible: false,
      formLabelWidth: "120px",
      rules: {},
    };
  },
  // mounted:在模板渲染成html后调用，通常是初始化页面完成后，再对html的dom节点进行一些需要的操作
  mounted() {
    this.search();
    // this.ss();
  },
  methods: {
      // 导出数据
      exportData() {
      // 1.定义表头对应关系
      const headers = {
        '办公物品申领id': 'suppliesId',
        '名称': 'suppliesName',
        '规格型号': 'suppliesType',
        '计量单位1：个2：本3：套': 'suppliesUnit',
        '单价': 'suppliesPrice',
        '申请人id': 'suppliesSysUsrId',
        '计量单位名称': 'suppliesUnitName',
        '状态Id': 'suppliesStaticId',
        '申请人id': 'suppliesProposerId',
        '状态Name': 'suppliesStaticName',
        '申请人Name': 'suppliesProposerName',
      }
      // 懒加载
      import('@/excel/Export2Excel').then(async excel => {
        // excel是引入文件（也就是@/ventor/Export2Excel）的导出对象
        // 获取所有的数据
        const  rows  =this.tableData;
        // console.log(rows);
    
        const data = this.formatJson(headers, rows) // 返回的data就是我们转化后的数据
        excel.export_json_to_excel({
          // 要求转出的表头是中文
          header: Object.keys(headers), // 表头 必填
          data, // //具体数据 必填
          filename: '办公用品申领excel', // 非必填
          autoWidth: true, // 非必填
          bookType: 'xlsx' // 非必填
        })
        // 拿到的数据是这种
        //  [{ username: 'xxx', mobile: 'xxx', ... }, { username: 'xxx', mobile: 'xxx', ... }]
        // 要转化的是如下这种
        // header: ['姓名', '手机号', '入职日期', ...]
        // data: [['张三', '138xxxxxxxx', '1992-08-04', ...], ['李四', '135xxxxxxxx', '1992-08-04', ...]]
      })
    },
    formatJson(headers, rows) {
      return rows.map(item => {
        // console.log(item)
        return Object.keys(headers).map(k => {
          if (headers[k] === 'timeOfEntry' || headers[k] === 'correctionTime') {
            return formatDate(item[headers[k]]) // 返回格式化之前的时间
          } else if (headers[k] === 'formOfEmployment') {
            return EmployeeEnum.hireType[item.formOfEmployment] ? EmployeeEnum.hireType[item.formOfEmployment] : '未知'
          }
          return item[headers[k]]
        })
      })
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.params.pageSize = val;
      this.search();
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.params.pageIndex = val;
      this.search();
    },
    async search() {
      const url = "/vueboot/supplies/list";
      const { data: res } = await this.$ajax.get(url, {
        params: {
          pageIndex: this.params.pageIndex,
          limit: this.params.pageSize,
          suppliesName: this.supper.suppliesName,
        },
        headers: {
          token: localStorage.getItem("token"),
        },
      });
      console.log(res);
      this.tableData = res.data.records;
      this.params.total = res.data.total;
    },
    // async ss() {
    //   const url = "/vueboot/examineApprove/geta";
    //   const { data: res } = await this.$ajax.get(url, {
    //     headers: {
    //       token: localStorage.getItem("token"),
    //     },
    //   });
    //   console.log(res);
    //   this.did = res.data;

    // },

    showAddDialog() {
      this.addDialogVisible = true;
    },
    showAddDialogs() {
      this.addDialogVisibles = true;
    },
    // 根据id删除
    async deletes(row) {
      console.log(row);
      const url = "/vueboot/supplies/deleteById";
      const { data: res } = await this.$ajax.get(url, {
        params: {
          suppliesId: row.suppliesId,
        },
        headers: {
          token: localStorage.getItem("token"),
        },
      });
      if (res.code > 0) {
        this.$message({
          message: "取消成功！",
          type: "success",
        });
        this.search();
      } else {
        this.$message.error(res.msg);
      }
    },
    addUser(supper) {
      this.$refs[supper].validate(async (valid) => {
        if (valid) {
          const url = "/vueboot/supplies/add";
          const { data: res } = await this.$ajax.post(
            url,
            this.supper,

            {
              // data:car,
              headers: {
                token: localStorage.getItem("token"),
              },
            }
          );
          console.log(res);
          if (res.data > 0) {
            this.$message({
              message: "添加成功",
              type: "success",
            });
            this.addDialogVisible = false;

            this.supper = {
              //办公物品申领id
              suppliesId: 0,
              //名称
              suppliesName: "",
              //规格型号
              suppliesType: "",
              //计量单位1：个2：本3：套
              suppliesUnit: 0,
              //单价
              suppliesPrice: 0,
              //申请人id
              suppliesSysUsrId: 0,
              suppliesUnitName: "", //计量单位名称
              suppliesStaticId: 0, //状态Id
              suppliesProposerId: 0, //申请人id
              suppliesStaticName: 0, //状态Name
              suppliesProposerName: 0, //申请人Name
            };
            this.search();
          } else {
            this.$message.error(res.msg);
            //  this.$message.error("添加失败");
          }
        }
      });
    },
  },
};
</script>
<style>
.breadcrumb {
  height: 30px;
}
</style>